package net.atos.spring;

import javax.validation.Valid;

import net.atos.spring.domain.Book;
import net.atos.spring.services.BookService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class BookController {

    @Autowired
    private BookService service;

    @RequestMapping(value = "/books", method = RequestMethod.POST)
    public String addBook(Model model, @Valid Book book, BindingResult bindingResult, @RequestParam(required = false) Integer index) {
	if (bindingResult.hasErrors()) {
	    model.addAttribute("books", service.getAllBooks());
	    model.addAttribute("count", service.countBooks());
	    return "books";
	}
	if (index == null) {
	    service.addBook(book);
	} else {
	    service.updateBook(book, index);
	}
	addListAndCount(model, new Book());
	return "redirect:books";
    }

    @RequestMapping(value = "/books", method = RequestMethod.GET)
    public String listOfBooks(Model model, @RequestParam(required = false) Integer index) {
	Book book;
	if (index != null) {
	    book = service.getById(index);
	} else {
	    book = new Book();
	}
	addListAndCount(model, book);
	return "books";
    }

    @RequestMapping(value = "/delete-book", method = RequestMethod.POST)
    public String deleteBook(Model model, @RequestParam Integer index) {
	service.removeBook(index);
	addListAndCount(model, new Book());
	return "redirect:books";
    }

    private void addListAndCount(Model model, Book book) {
	model.addAttribute("books", service.getAllBooks());
	model.addAttribute("count", service.countBooks());
	model.addAttribute("book", book);
    }
}
